<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\Controller;
use App\Http\Requests\Api\AdminuserRequest;
use App\Models\AdminUser;
use function foo\func;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{
    //
    protected $redirectTo = '/admin';

   /* public function __construct()
    {
        $this->middleware('guest.admin', ['except' => 'logout']);
    }*/

    //显示后台登录模板
//    public function showlogin(){
//        return view('admin.login');
//    }

    //登录
    public function login(AdminUser $adminUser,Request $request){
       /* if(Auth::guard('admin')->attempt(['username'=>$request->username, 'password'=>$request->password])){
            $token=str_random(10);
            //缓存
            Cache::put($token,'admin_' . Auth::guard('admin')->id() , 120);
            return $this->response->array(['message'=>'登录成功','token'=>$token])->setStatusCode(200);
        }else{
//            return back()->with('error', '账号或密码错误')->withInput();
            return $this->response->array(['账号或密码错误'])->setStatusCode(401);
        }*/


        $credentials['username'] = $request->username;
        $credentials['password'] = $request->password;


        if (! $token = Auth::guard('admin')->attempt($credentials)){
            return $this->response->errorUnauthorized('用户名或者密码错误');
        }



            return $this->responseWithToken($token)->setStatusCode(201);
    }

    //退出登录
    public function logout(){
        if (Auth::guard('admin')->user()){
            Auth::guard('admin')->logout();
        }
        return with('success');
    }

    //重写验证时使用的用户名字段
    public function username(){
        return 'username';
    }

    public function responseWithToken($token){
        return $this->response->array([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => Auth::guard('admin')->factory()->getTTL()*60,
        ]);
    }


}



